<template>
  <div class="users">
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 搜索框 -->
    <el-input placeholder="请输入搜索关键字" v-model="inputValue" class="input-with-select">
      <el-button @click="searchUser" slot="append" icon="el-icon-search"></el-button>
    </el-input>
    <!-- 添加用户 -->
    <el-button @click="showAdd" class="addBtn" type="success" plain>添加用户</el-button>
    <!-- 表格 -->
    <template>
      <el-table :data="userList" border>
        <el-table-column prop="username" label="姓名"></el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column prop="mobile" label="电话"></el-table-column>
        <el-table-column prop label="用户状态">
          <!-- 开关 -->
          <template v-slot:default="obj">
            <el-switch
              @change="changeState(obj.row.id,obj.row.mg_state)"
              v-model="obj.row.mg_state"
              active-color="#13ce66"
              inactive-color="#ff4949"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column prop label="操作" width="300px">
          <!-- 匿名插槽 -->
          <template v-slot:default="{row}">
            <el-button @click="showEdit(row)" size="mini" plain type="primary" icon="el-icon-edit"></el-button>
            <el-button
              @click="delUser(row.id)"
              size="mini"
              plain
              type="danger"
              icon="el-icon-delete"
            ></el-button>
            <el-button @click="showUser(row)" size="mini" plain type="success" icon="el-icon-check">分配角色</el-button>
          </template>
        </el-table-column>
      </el-table>
    </template>
    <!-- 分页 -->
    <el-pagination
      background
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="pagenum"
      :page-sizes="[2, 4, 6, 8]"
      :page-size="pagesize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
    ></el-pagination>

    <!-- 添加对话框 -->
    <el-dialog @close='closeDialog' title="添加用户"  :visible.sync="dialogVisible" width="40%">
      <!-- 内容部分 -->
      <el-form ref="form" :rules='rules' :model="form" label-width="80px">
        <el-form-item label="用户名"  prop='username'>
          <el-input v-model="form.username" placeholder="请输入用户名"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop='password'>
          <el-input v-model="form.password" placeholder="请输入密码" type="password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop='email'>
          <el-input v-model="form.email" placeholder="请输入邮箱"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop='mobile'>
          <el-input v-model="form.mobile" placeholder="请输入手机号"></el-input>
        </el-form-item>
      </el-form>
      <!-- 具名插槽 -->
      <template v-slot:footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addUser">确 定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 修改框 -->
    <el-dialog title="添加用户"  :visible.sync="editVisible" width="30%">
      <!-- 内容部分 -->
      <el-form ref="editform" :rules='rules' :model="editform" label-width="80px">
        <el-form-item label="用户名" >
         <el-tag type="info">{{editform.username}}</el-tag>
        </el-form-item>
        <el-form-item label="邮箱" prop='email'>
          <el-input v-model="editform.email" placeholder="请输入邮箱"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop='mobile'>
          <el-input v-model="editform.mobile" placeholder="请输入手机号"></el-input>
        </el-form-item>
      </el-form>
      <!-- 具名插槽 -->
      <template v-slot:footer>
        <span class="dialog-footer">
          <el-button @click="editVisible = false">取 消</el-button>
          <el-button type="primary" @click="editUser">确 定</el-button>
        </span>
      </template>
    </el-dialog>
<!-- --------------------------------------------------------------- -->
    <!-- 分配框 -->
      <el-dialog title="分配角色"  :visible.sync="allotVisible" width="40%">
      <!-- 内容部分 -->
      <el-form  :model="allotform" label-width="80px">
        <el-form-item label="用户名" >
         <el-tag type="info">{{allotform.username}}</el-tag>
        </el-form-item>

         <el-form-item label="角色列表">
            <!-- v-model 绑定的就是将来要提交的选中的 option的value (id) -->
            <!-- assignForm.rid 不仅可以用于获取, 也可以用于设置 -->
            <el-select v-model="allotform.rid" placeholder="请选择">
              <el-option
                v-for="item in options"
                :key="item.id"

                :label="item.roleName"
                :value="item.id">
              </el-option>
            </el-select>
        </el-form-item>
      </el-form>
      <!-- 具名插槽 -->
      <template v-slot:footer>
        <span class="dialog-footer">
          <el-button @click="allotVisible = false">取 消</el-button>
          <el-button @click="assignRole" type="primary">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
export default {
  methods: {
    handleSizeChange (val) {
      // console.log(`每页 ${val} 条`)
      this.pagesize = val
      // 重置当前页
      this.pagenum = 1
      this.getUserList()
    },
    handleCurrentChange (val) {
      // console.log(`当前页: ${val}`)
      this.pagenum = val
      this.getUserList()
    },
    async getUserList () {
      const { data, meta } = await this.$axios.get('users', {
        // 配置params
        params: {
          query: this.query,
          pagenum: this.pagenum,
          pagesize: this.pagesize
        }
      })
      if (meta.status === 200) {
        this.userList = data.users

        this.total = data.total
      } else {
        this.$message.error(meta.msg)
      }
    },
    searchUser () {
      // 点击时。需要修改搜索条件
      this.query = this.inputValue
      // 如果页码出现了大量的变化, 一般重置成第一页开始展示
      this.pagenum = 1
      // 根据搜索条件, 发送对应的ajax, 进行渲染
      this.getUserList()
    },
    async changeState (id, type) {
      const { meta } = await this.$axios.put(`users/${id}/state/${type}`)
      if (meta.status === 200) {
        this.$message.success(meta.msg)
      } else {
        this.$message.error(meta.msg)
      }
    },

    async delUser (id) {
      try {
        await this.$confirm('您确认要删除吗？', '温馨提示', {
          type: 'warning'
        })
        const { meta } = await this.$axios.delete(`users/${id}`)
        if (meta.status === 200) {
          this.$message.success(meta.msg)
          if (this.userList.length === 1 && this.pagenum > 1) {
            this.pagenum--
          }
          // 重新渲染
          this.getUserList()
        } else {
          this.$message.error(meta.msg)
        }
      } catch (err) {
        console.log(err)
      }
    },
    // 显示添加对话框
    showAdd () {
      this.dialogVisible = true
    },
    // 添加功能
    async addUser () {
      try {
        // 对表单进行校验。el提供的方法
        await this.$refs.form.validate()
        const { meta } = await this.$axios.post('users', this.form)
        if (meta.status === 201) {
          this.$message.success(meta.msg)
          // 关闭对话框
          this.dialogVisible = false
          // 重新渲染最后一页
          this.total++
          this.pagenum = Math.ceil(this.total / this.pagesize)
          this.getUserList()
        } else {
          this.$message.error(meta.msg)
        }
      } catch (e) {
        console.log(e)
      }
    },
    // 添加确认后清空对话框
    closeDialog () {
      this.$refs.form.resetFields()
    },
    // 显示修改对话框
    showEdit (row) {
      this.editVisible = true
      this.editform.id = row.id
      this.editform.username = row.username
      this.editform.email = row.email
      this.editform.mobile = row.mobile
    },
    // 点击确认修改
    async editUser () {
      try {
        await this.$refs.editform.validate()
        const { id, email, mobile } = this.editform
        const { meta } = await this.$axios.put(`users/${this.editform.id}`, { email, mobile
        })
        if (meta.status === 200) {
          this.$message.success(meta.msg)
          this.editVisible = false
          this.getUserList()
        } else {
          this.$message.error(meta.msg)
        }
      } catch (e) {
        console.log(e)
      }
    },
    async showUser (row) {
      this.allotVisible = true
      console.log(row)

      this.allotform.id = row.id
      this.allotform.username = row.username
      const resUser = await this.$axios.get(`users/${row.id}`)
      if (resUser.meta.status === 200) {
        const rid = resUser.data.rid
        this.allotform.rid = rid === -1 ? '' : rid
      }

      const { data, meta } = await this.$axios.get('roles')
      if (meta.status === 200) {
        this.options = data
      } else {
        this.$message.error(meta.msg)
      }
    },
    async assignRole () {
      const { id, rid } = this.allotform
      if (rid === '') {
        this.$message.error('请选择角色')
        return
      }
      // 发送分配的ajax请求
      const { meta } = await this.$axios.put(`users/${id}/role`, { rid })
      if (meta.status === 200) {
        this.$message.success(meta.msg)
        // 关闭对话框
        this.allotVisible = false
        // 重新渲染
        this.getUserList()
      } else {
        this.$message.error(meta.msg)
      }
    }

  },

  data () {
    return {
      inputValue: '', // input搜索框
      query: '', // 搜索条件
      pagenum: 1, // 当前页
      pagesize: 2, // 每页条数
      userList: [], // 用户列表
      total: 0, // 总条数
      dialogVisible: false, // 对话框默认
      editVisible: false, // 修改对话框
      allotVisible: false, // 分配对话框
      form: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: ['blur', 'change'] },
          { min: 3, max: 12, message: '长度在 3 到 12 个字符', trigger: ['blur', 'change'] }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: ['blur', 'change'] },
          { min: 3, max: 12, message: '长度在 3 到 12 个字符', trigger: ['blur', 'change'] }
        ],
        email: [
          { type: 'email', message: '请输入正确的邮箱', trigger: ['blur', 'change'] }

        ],
        mobile: [
          { pattern: /^1[1-9]\d{9}$/, message: '请输入正确的手机号', trigger: ['change', 'blur'] }
        ]
      },
      editform: {
        id: '',
        username: '',
        email: '',
        mobile: ''
      },
      allotform: {
        username: '',
        id: '',
        rid: ''
      },
      options: []

    }
  },
  // 渲染页面
  created () {
    this.getUserList()
  }
}
</script>

<style lang='less' scopet>
.users {

  .input-with-select {
    width: 300px;
    margin-bottom: 10px;
  }
  .addBtn {
    margin: 0 20px;
  }
}
</style>
